package com.wholesmart.common.security.authorization;

import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import com.wholesmart.service.UserService;

/**
 * RbacService的默认实现
 * 
 * @author dyw
 * @date 2019年11月4日
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {
	@Autowired
	private UserService userService;
	/** 路径匹配工具 */
	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
		Object principal = authentication.getPrincipal();
		boolean hasPermission = false;
		if (principal instanceof UserDetails) {
			String username = ((UserDetails) principal).getUsername();
			// 读取用户所拥有权限的所有URL
			Set<String> urls = userService.getAccessUrlsByUsername(username);
			if (urls == null) {
				hasPermission = false;
			} else {
				for (String url : urls) {
					if (antPathMatcher.match(url, request.getRequestURI())) {
						hasPermission = true;
						break;
					}
				}
			}
		}
		return hasPermission;
	}
}
